/* Copyright - Apache License 2.0
 * 
 * The project "kyou" is
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *      http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.kyou.pack.segment;

import java.nio.charset.Charset;

import net.kyou.pack.PackContext;
import net.kyou.pack.StyleItem;
import net.kyou.pack.segment.param.Param;
import net.kyou.util.KyouByteOutputStream;

import org.w3c.dom.Element;

/**
 * 参数段
 * <p>
 * 可以向参数段指定一个参数，在组包过程中计算该参数的值，并将该值以该参数段自定义的方式输出到流中。
 * </p>
 * 
 * @author NuclearG (<a href="mailto:nuclearg@163.com">nuclearg@163.com</a>)
 */
abstract class ParamSegment extends Segment {
    /**
     * 该参数段的参数
     */
    private final Param param;

    /**
     * 初始化一个参数段
     * 
     * @param e
     *            XML元素
     * @param encoding
     *            整篇报文的编码
     * @param style
     *            本段隶属于的组包样式单元
     */
    ParamSegment(Element e, Charset encoding, StyleItem style) {
        super(style);

        this.param = Param.__new(e.getTextContent(), this, encoding);

        SegmentTag tag = this.getClass().getAnnotation(SegmentTag.class);
        Param.__checkType(param, tag.type());
    }

    @Override
    public void __export(PackContext context, KyouByteOutputStream s) {
        this.export(this.param.__eval(context), context, s);
    }

    /**
     * 将参数的结果输出到流中
     * 
     * @param v
     *            参数的计算结果
     * @param context
     *            组包上下文
     */
    abstract void export(Object v, PackContext context, KyouByteOutputStream s);
}
